package com.iflytek.testtoastwindow;

import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Build;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.AbsoluteLayout;

import com.iflytek.testtoastwindow.utils.PermissionUtil;
import com.iflytek.testtoastwindow.utils.PhoneType;
import com.iflytek.testtoastwindow.utils.RomUtil;

/**
 * 
 * <b>来电秀悬浮窗管理器</b>
 * @author leisu@iflytek.com
 * @since 2015年11月25日 下午2:42:23
 */
public class PhoneShowAlertWindowManager {

	static WindowManager mWindowManager;
    private static View currentShowView = null;

    private static void initWindowManager(Context context)
    {
    	if(null == mWindowManager)
        {
        	mWindowManager = (WindowManager)context.getApplicationContext().getSystemService(Context.WINDOW_SERVICE);	
        }
    }
    
    /**
     * 显示悬浮窗
     * @param context
     * @param view 需要被显示的view
     * @param isDraggable
     */
    public static void showTopWindow(final Context context, final View view, boolean isDraggable)
    {

    	if(null == view)
    	{
    		return;
    	}
    	initWindowManager(context);
    	
    	// 清空之前的view
//        clearCurrentTopWindow(context, false);
        
        final DraggableFrameLayout dragLayout = new DraggableFrameLayout(context);
        dragLayout.setDraggable(isDraggable);

        dragLayout.setOnKeyEventListener(new DraggableFrameLayout.OnKeyEventListener() {
            @Override
            public boolean onKeyDown(int keyCode, KeyEvent event) {
                return false;
            }

            @Override
            public boolean onKeyUp(int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    clearTopWindow(context, dragLayout);
                    return true;
                }
                return false;
            }
        });
        //dragLayout.setDragScreenLimit(PhoneShowAPI.isPhoneShowWindowDragScreenLimit());

        AbsoluteLayout.LayoutParams lp = new AbsoluteLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT,0, 0);

        dragLayout.addView(view, lp);
        //dragLayout.addView(view, android.widget.FrameLayout.LayoutParams.WRAP_CONTENT, android.widget.FrameLayout.LayoutParams.WRAP_CONTENT);


        // 保存当前的view
        currentShowView = dragLayout;


        WindowManager.LayoutParams wmParams = new WindowManager.LayoutParams();

        wmParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR; // 用这个配置项，是普通应用能够创建的最高级别，360、qq通讯录之类就用的这个，谁后添加谁就在最上面，但是这个也会遮挡住很多手机的快捷接听界面，影响用户体验
//        wmParams.type = WindowManager.LayoutParams.TYPE_PRIORITY_PHONE; // 这个配置项会在电话接听界面之上，在快捷接听界面之下，不会影响用户接听电话

        // 小米、华为系统，并且没有获取到悬浮窗权限，则使用TYPE_TOAST
//        if((RomUtil.getPhoneType() == PhoneType.PHONE_TYPE_XIAOMI || RomUtil.getPhoneType() == PhoneType.PHONE_TYPE_HUAWEI) &&

//        if(PermissionUtil.isCanUse())
//        {
//            // 没有获取到悬浮窗权限，直接使用TYPE_TOAST
//            if(PermissionUtil.checkOp(context, 24) != PermissionUtil.CheckPermissionResultType.RESULT_TYPE_ALLOW)
//            {
//                if(RomUtil.getPhoneType()== PhoneType.PHONE_TYPE_HUAWEI)
//                {
//                    wmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
//                }
//                else
//                {
//                    wmParams.type = WindowManager.LayoutParams.TYPE_TOAST;
//                }
//            }
//        }
//        else
//        {
//            if(RomUtil.getPhoneType()==PhoneType.PHONE_TYPE_HUAWEI)
//            {
//                wmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
//            } else
//            {
//                wmParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
//            }
//        }

        wmParams.format = PixelFormat.RGBA_8888;

        wmParams.flags = WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |  WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;

        int oriFlags = wmParams.flags;
        if (hasFlag(oriFlags, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)) {
            oriFlags ^= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        }

        wmParams.flags = oriFlags;

        //调整悬浮窗显示的停靠位置为顶部水平居中
        wmParams.gravity = Gravity.LEFT | Gravity.TOP;

        // 以屏幕左上角为原点，设置x、y初始值
        wmParams.x = 0;
        wmParams.y = 0;

        //设置悬浮窗口长宽
        wmParams.width =WindowManager.LayoutParams.WRAP_CONTENT;
        wmParams.height =WindowManager.LayoutParams.WRAP_CONTENT;

        mWindowManager.addView(currentShowView, wmParams);

    	AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);
        alphaAnimation.setDuration(200);
        view.startAnimation(alphaAnimation);
    }



    public static void clearTopWindow(Context context, View view) {
        if (view != null && view.isShown()) {
        	initWindowManager(context);
        	
        	// 清除悬浮窗
            mWindowManager.removeView(view);
        }
    }

    public static void clearCurrentTopWindow(final Context context)
    {
    	clearCurrentTopWindow(context, true);
    }
    public static void clearCurrentTopWindow(final Context context, boolean isAnim)
    {

    	if(null != currentShowView)
    	{
            clearTopWindow(context, currentShowView);
    	}
    	currentShowView = null;
    }
  
    public static View getCurrentShowView()
    {
    	if(null != currentShowView)
    	{
    		return ((ViewGroup)currentShowView).getChildAt(0);
    	}
    	return null;
    }

    private static boolean hasFlag(int flags, int flag) {
        return (flags & flag) > 0;
    }
}
